// pages/orderTrajectory/orderTrajectory.js
const orderService = require('../../../../api/orderService.js')
let map;

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    position: {},
    scale: 18,
    markers: [],
    polyline: [],
    status: 'step1', //step1 step2 step3 step4
    sellerPhone: '021-62626262',
    riderPhone: '13333333333'
  },
  regionchange(e) {
    console.log(e.type)
  },
  markertap(e) {
    console.log(e.markerId)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.systemInfo)
    const self = this
    map = wx.createMapContext('map')
    console.log(map)
    if (options.location) {
      const location = JSON.parse(options.location)
      self.setData({
        position: {
          latitude: location.user.latitude,
          longitude: location.user.longitude
        }
      })
      console.log(location)
      self.getOrderLocation(location.store, location.user)
    } else {
      // 调用接口查询订单数据，获取用户及门店经纬度
    }
    orderService.getRideLocation(options.orderId).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 根据经纬度渲染订单轨迹
   * @param store 门店经纬度信息
   * @param user 用户经纬度信息
   */
  getOrderLocation: function (store, user) {
    const self = this
    const systemInfo = app.globalData.systemInfo
    let markers = []
    // 标记用户位置
    markers.push({
      iconPath: "../../../../image/iconTrajectoryAvatarUrlDefault.png",
      id: 0,
      latitude: user.latitude,
      longitude: user.longitude,
      width: 72 / 750 * systemInfo.windowWidth,
      height: 97 / 750 * systemInfo.windowWidth,
      zIndex: 0
    })
    // 标记门店位置
    markers.push({
      iconPath: "../../../../image/iconTrajectoryBusinessXf.png",
      id: 2,
      latitude: store.latitude,
      longitude: store.longitude,
      width: 72 / 750 * systemInfo.windowWidth,
      height: 97 / 750 * systemInfo.windowWidth,
      callout: {
        content: '商家已接单',
        bgColor: '#ffffff',
        display: 'ALWAYS',
        padding: 24 / 750 * systemInfo.windowWidth,
        borderRadius: 70,
        fontSize: 24 / 750 * systemInfo.windowWidth,
      },
      zIndex: 0
    })
    // 模拟配送员位置
    let longitude = store.longitude
    let latitude = store.latitude
    longitude = longitude + 0.002
    latitude = latitude + 0.002
    var markersWidth = 110 / 750 * systemInfo.windowWidth, //设置图片显示宽度，
      markersHeight = 139 / 750 * systemInfo.windowWidth; //计算的高度值   
    markers.push({
      iconPath: "../../../../image/iconTrajectoryDistributorRider1.png",
      id: 1,
      latitude: store.latitude,
      longitude: longitude,
      width: markersWidth,
      height: markersHeight,
      callout: {
        content: '配送中|距您2.8km',
        bgColor: '#ffffff',
        display: 'ALWAYS',
        padding: 24 / 750 * systemInfo.windowWidth,
        borderRadius: 70,
        fontSize: 24 / 750 * systemInfo.windowWidth,
      },
      zIndex: 2
    })

    self.setData({
      markers: markers
    })
    map.getRegion({
      success: function (res) {
        console.log(res)
      }
    })
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      self.drawAvatarUrl()
    }
  },
  drawAvatarUrl: function () {
    var that = this
    var imgPath = app.globalData.userInfo.wxaUser.avatarUrl //头像的图片
    wx.downloadFile({
      url: app.globalData.userInfo.wxaUser.avatarUrl,
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          console.log(res.tempFilePath)
          imgPath = res.tempFilePath
          console.log(imgPath)
          var bgImgPath = '../../../../image/iconTrajectoryAvatarUrlBg.png' //背景图
          var width = 72
          var height = 97
          const ctx = wx.createCanvasContext('myCanvas', this) //创建 canvas 绘图上下文
          ctx.drawImage(bgImgPath, 0, 0, width, height) //将背景图绘制到画布中
          //绘制头像，这里绘制圆形头像算是一个小重点
          ctx.save()
          ctx.beginPath()
          //首先绘制一个圆形的弧线，大小位置根据你的需求而定，也就是说你想让它放在什么位置，就让它放在什么位置
          ctx.arc(36, 36, 33, 0, 2 * Math.PI)
          //使用clip() 方法从原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.clip()
          ctx.drawImage(imgPath, 3, 3, 65, 65)
          ctx.restore()
          ctx.draw(true)
          //将canvas画布转化为图片
          setTimeout(() => {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 72,
              height: 97,
              destWidth: 72,
              destHeight: 97,
              canvasId: 'myCanvas',
              success: function (res) {
                console.log(res.tempFilePath);
                /* 这里 就可以显示之前写的 预览区域了 把生成的图片url给image的src */
                let markers = that.data.markers
                if (markers.length > 0) {
                  markers.forEach((item, index) => {
                    if (item.id === 0) {
                      item.iconPath = res.tempFilePath
                    }
                  });
                }
                that.setData({
                  imagePath: res.tempFilePath,
                  markers: markers
                })
              },
              fail: function (res) {
                console.log(res)
              }
            })
          }, 200);
        }
      },
      fail(error) {
        console.log(error)
      }
    })

  },
  refreshTrajectory: function () {
    this.setData({
      scale: 18,
      markers: [],
      polyline: [],
    })
    this.onLoad(this.options)
  },
  handleClose: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  contactSeller: function () {
    const that = this
    wx.showModal({
      title: '提示',
      content: '您将拨打以下电话联系卖家:' + that.data.sellerPhone,
      success(res) {
        if (res.confirm) {
          that.callPhone(that.data.sellerPhone)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  contactRider: function () {
    const that = this
    wx.showModal({
      title: '提示',
      content: '您将拨打以下电话联系骑手:' + that.data.riderPhone,
      success(res) {
        if (res.confirm) {
          that.callPhone(that.data.riderPhone)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  callPhone: function (phone) {
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})